<template>
  <div class="auth-page">
    <div class="container">
      <div class="row justify-content-center">
        <div class="col-md-6 col-lg-5">
          <div class="card auth-card animate-fadeInUp">
            <div class="card-header text-center border-0 bg-transparent">
              <h3 class="card-title fw-bold mb-0">
                <i class="bi bi-person-circle me-2"></i>
                {{ isLogin ? '登录' : '注册' }}
              </h3>
            </div>
            <div class="card-body p-4">
              <!-- 切换登录/注册 -->
              <div class="auth-switch mb-4 text-center">
                <div class="btn-group" role="group">
                  <button 
                    type="button" 
                    class="btn"
                    :class="isLogin ? 'btn-primary' : 'btn-outline-primary'"
                    @click="switchToLogin"
                  >
                    登录
                  </button>
                  <button 
                    type="button" 
                    class="btn"
                    :class="!isLogin ? 'btn-primary' : 'btn-outline-primary'"
                    @click="switchToRegister"
                  >
                    注册
                  </button>
                </div>
              </div>

              <!-- 登录表单 -->
              <form v-if="isLogin" @submit.prevent="handleLogin" class="auth-form">
                <div class="mb-3">
                  <label for="loginUsername" class="form-label">
                    <i class="bi bi-person me-1"></i>用户名
                  </label>
                  <input 
                    type="text" 
                    class="form-control" 
                    id="loginUsername"
                    v-model="loginForm.username"
                    :class="{ 'is-invalid': errors.loginUsername }"
                    placeholder="请输入用户名"
                    required
                  >
                  <div v-if="errors.loginUsername" class="invalid-feedback">
                    {{ errors.loginUsername }}
                  </div>
                </div>
                
                <div class="mb-3">
                  <label for="loginPassword" class="form-label">
                    <i class="bi bi-lock me-1"></i>密码
                  </label>
                  <div class="input-group">
                    <input 
                      :type="showPassword ? 'text' : 'password'" 
                      class="form-control" 
                      id="loginPassword"
                      v-model="loginForm.password"
                      :class="{ 'is-invalid': errors.loginPassword }"
                      placeholder="请输入密码"
                      required
                    >
                    <button 
                      class="btn btn-outline-secondary" 
                      type="button"
                      @click="togglePassword"
                    >
                      <i class="bi" :class="showPassword ? 'bi-eye-slash' : 'bi-eye'"></i>
                    </button>
                    <div v-if="errors.loginPassword" class="invalid-feedback">
                      {{ errors.loginPassword }}
                    </div>
                  </div>
                </div>

                <div class="mb-3 form-check">
                  <input 
                    type="checkbox" 
                    class="form-check-input" 
                    id="rememberMe"
                    v-model="loginForm.rememberMe"
                  >
                  <label class="form-check-label" for="rememberMe">
                    记住我
                  </label>
                </div>

                <button type="submit" class="btn btn-primary w-100 mb-3" :disabled="isLoading">
                  <span v-if="isLoading" class="spinner-border spinner-border-sm me-2"></span>
                  <i v-else class="bi bi-box-arrow-in-right me-2"></i>
                  {{ isLoading ? '登录中...' : '登录' }}
                </button>
              </form>

              <!-- 注册表单 -->
              <form v-else @submit.prevent="handleRegister" class="auth-form">
                <div class="mb-3">
                  <label for="registerUsername" class="form-label">
                    <i class="bi bi-person me-1"></i>用户名
                  </label>
                  <input 
                    type="text" 
                    class="form-control" 
                    id="registerUsername"
                    v-model="registerForm.username"
                    :class="{ 'is-invalid': errors.registerUsername }"
                    placeholder="请输入用户名（3-20个字符）"
                    required
                  >
                  <div v-if="errors.registerUsername" class="invalid-feedback">
                    {{ errors.registerUsername }}
                  </div>
                </div>

                <div class="mb-3">
                  <label for="registerEmail" class="form-label">
                    <i class="bi bi-envelope me-1"></i>邮箱
                  </label>
                  <input 
                    type="email" 
                    class="form-control" 
                    id="registerEmail"
                    v-model="registerForm.email"
                    :class="{ 'is-invalid': errors.registerEmail }"
                    placeholder="请输入邮箱地址"
                    required
                  >
                  <div v-if="errors.registerEmail" class="invalid-feedback">
                    {{ errors.registerEmail }}
                  </div>
                </div>
                
                <div class="mb-3">
                  <label for="registerPassword" class="form-label">
                    <i class="bi bi-lock me-1"></i>密码
                  </label>
                  <div class="input-group">
                    <input 
                      :type="showPassword ? 'text' : 'password'" 
                      class="form-control" 
                      id="registerPassword"
                      v-model="registerForm.password"
                      :class="{ 'is-invalid': errors.registerPassword }"
                      placeholder="请输入密码（至少6位）"
                      required
                    >
                    <button 
                      class="btn btn-outline-secondary" 
                      type="button"
                      @click="togglePassword"
                    >
                      <i class="bi" :class="showPassword ? 'bi-eye-slash' : 'bi-eye'"></i>
                    </button>
                    <div v-if="errors.registerPassword" class="invalid-feedback">
                      {{ errors.registerPassword }}
                    </div>
                  </div>
                </div>

                <div class="mb-3">
                  <label for="confirmPassword" class="form-label">
                    <i class="bi bi-lock-fill me-1"></i>确认密码
                  </label>
                  <input 
                    :type="showPassword ? 'text' : 'password'" 
                    class="form-control" 
                    id="confirmPassword"
                    v-model="registerForm.confirmPassword"
                    :class="{ 'is-invalid': errors.confirmPassword }"
                    placeholder="请再次输入密码"
                    required
                  >
                  <div v-if="errors.confirmPassword" class="invalid-feedback">
                    {{ errors.confirmPassword }}
                  </div>
                </div>

                <div class="mb-3 form-check">
                  <input 
                    type="checkbox" 
                    class="form-check-input" 
                    id="agreeTerms"
                    v-model="registerForm.agreeTerms"
                    :class="{ 'is-invalid': errors.agreeTerms }"
                    required
                  >
                  <label class="form-check-label" for="agreeTerms">
                    我同意<a href="#" class="text-decoration-none">服务条款</a>和<a href="#" class="text-decoration-none">隐私政策</a>
                  </label>
                  <div v-if="errors.agreeTerms" class="invalid-feedback">
                    {{ errors.agreeTerms }}
                  </div>
                </div>

                <button type="submit" class="btn btn-primary w-100 mb-3" :disabled="isLoading">
                  <span v-if="isLoading" class="spinner-border spinner-border-sm me-2"></span>
                  <i v-else class="bi bi-person-plus me-2"></i>
                  {{ isLoading ? '注册中...' : '注册' }}
                </button>
              </form>

              <!-- 错误/成功消息 -->
              <div v-if="message.text" class="alert alert-dismissible fade show" :class="message.type === 'success' ? 'alert-success' : 'alert-danger'">
                <i class="bi me-2" :class="message.type === 'success' ? 'bi-check-circle' : 'bi-exclamation-triangle'"></i>
                {{ message.text }}
                <button type="button" class="btn-close" @click="clearMessage"></button>
              </div>

               <!-- 已注册用户提示 -->
               <div v-if="registeredUsers.length > 0" class="text-center mt-3">
                 <div class="registered-users-info">
                   <small class="text-muted">
                     <i class="bi bi-info-circle me-1"></i>
                     已注册用户：
                   </small>
                   <div class="user-list mt-2">
                     <small 
                       v-for="user in registeredUsers" 
                       :key="user.id"
                       class="badge bg-light text-dark me-2 mb-1"
                       @click="quickFillUser(user.username)"
                       style="cursor: pointer;"
                       :title="`点击快速填入用户名: ${user.username}`"
                     >
                       {{ user.username }}
                     </small>
                   </div>
                 </div>
               </div>
               
               <!-- 无用户提示 -->
               <div v-else class="text-center mt-3">
                 <small class="text-muted">
                   <i class="bi bi-info-circle me-1"></i>
                   暂无注册用户，请先注册一个账号
                 </small>
               </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Auth',
  data() {
    return {
      isLogin: true,
      showPassword: false,
      isLoading: false,
      
      // 登录表单
      loginForm: {
        username: '',
        password: '',
        rememberMe: false
      },
      
      // 注册表单
      registerForm: {
        username: '',
        email: '',
        password: '',
        confirmPassword: '',
        agreeTerms: false
      },
      
      // 错误信息
      errors: {},
      
      // 消息提示
      message: {
        text: '',
        type: ''
      },
      
      // 已注册用户列表
      registeredUsers: []
    }
  },
  
  methods: {
    // 切换到登录
    switchToLogin() {
      this.isLogin = true
      this.clearErrors()
      this.clearMessage()
    },
    
    // 切换到注册
    switchToRegister() {
      this.isLogin = false
      this.clearErrors()
      this.clearMessage()
    },
    
    // 切换密码显示
    togglePassword() {
      this.showPassword = !this.showPassword
    },
    
    // 清除错误信息
    clearErrors() {
      this.errors = {}
    },
    
    // 清除消息
    clearMessage() {
      this.message = { text: '', type: '' }
    },
    
    // 显示消息
    showMessage(text, type = 'error') {
      this.message = { text, type }
      
      // 3秒后自动清除消息
      setTimeout(() => {
        this.clearMessage()
      }, 3000)
    },
    
    // 验证登录表单
    validateLoginForm() {
      this.clearErrors()
      let isValid = true
      
      if (!this.loginForm.username.trim()) {
        this.errors.loginUsername = '请输入用户名'
        isValid = false
      }
      
      if (!this.loginForm.password) {
        this.errors.loginPassword = '请输入密码'
        isValid = false
      }
      
      return isValid
    },
    
    // 验证注册表单
    validateRegisterForm() {
      this.clearErrors()
      let isValid = true
      
      // 用户名验证
      if (!this.registerForm.username.trim()) {
        this.errors.registerUsername = '请输入用户名'
        isValid = false
      } else if (this.registerForm.username.length < 3 || this.registerForm.username.length > 20) {
        this.errors.registerUsername = '用户名长度应为3-20个字符'
        isValid = false
      }
      
      // 邮箱验证
      if (!this.registerForm.email.trim()) {
        this.errors.registerEmail = '请输入邮箱地址'
        isValid = false
      } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.registerForm.email)) {
        this.errors.registerEmail = '请输入有效的邮箱地址'
        isValid = false
      }
      
      // 密码验证
      if (!this.registerForm.password) {
        this.errors.registerPassword = '请输入密码'
        isValid = false
      } else if (this.registerForm.password.length < 6) {
        this.errors.registerPassword = '密码长度至少6位'
        isValid = false
      }
      
      // 确认密码验证
      if (!this.registerForm.confirmPassword) {
        this.errors.confirmPassword = '请确认密码'
        isValid = false
      } else if (this.registerForm.password !== this.registerForm.confirmPassword) {
        this.errors.confirmPassword = '两次输入的密码不一致'
        isValid = false
      }
      
      // 协议同意验证
      if (!this.registerForm.agreeTerms) {
        this.errors.agreeTerms = '请同意服务条款和隐私政策'
        isValid = false
      }
      
      return isValid
    },
    
     // 处理登录
     async handleLogin() {
       if (!this.validateLoginForm()) {
         return
       }
       
       this.isLoading = true
       this.clearMessage()
       
       try {
         // 模拟API请求延迟
         await new Promise(resolve => setTimeout(resolve, 1000))
         
         // 获取本地存储的用户数据
         const users = JSON.parse(localStorage.getItem('blog_users') || '[]')
         
         // 检查是否有注册用户
         if (users.length === 0) {
           this.showMessage('暂无注册用户，请先注册账号')
           return
         }
         
         // 查找用户名
         const existingUser = users.find(u => u.username === this.loginForm.username)
         
         if (!existingUser) {
           this.showMessage('用户名不存在，请检查用户名或先注册')
           return
         }
         
         // 验证密码
         if (existingUser.password !== this.loginForm.password) {
           this.showMessage('密码错误，请重新输入')
           return
         }
         
         // 登录成功
         const loginData = {
           user: {
             id: existingUser.id,
             username: existingUser.username,
             email: existingUser.email,
             loginTime: new Date().toISOString()
           },
           rememberMe: this.loginForm.rememberMe
         }
         
         // 保存登录状态
         if (this.loginForm.rememberMe) {
           localStorage.setItem('blog_auth', JSON.stringify(loginData))
         } else {
           sessionStorage.setItem('blog_auth', JSON.stringify(loginData))
         }
         
         this.showMessage('登录成功！正在跳转...', 'success')
         
         // 跳转到首页
         setTimeout(() => {
           this.$router.push('/')
         }, 1500)
         
       } catch (error) {
         this.showMessage('登录失败，请重试')
       } finally {
         this.isLoading = false
       }
     },
    
    // 处理注册
    async handleRegister() {
      if (!this.validateRegisterForm()) {
        return
      }
      
      this.isLoading = true
      this.clearMessage()
      
      try {
        // 模拟API请求延迟
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        // 检查用户名是否已存在
        const users = JSON.parse(localStorage.getItem('blog_users') || '[]')
        const existingUser = users.find(u => 
          u.username === this.registerForm.username || 
          u.email === this.registerForm.email
        )
        
        if (existingUser) {
          if (existingUser.username === this.registerForm.username) {
            this.errors.registerUsername = '用户名已存在'
          }
          if (existingUser.email === this.registerForm.email) {
            this.errors.registerEmail = '邮箱已被注册'
          }
          return
        }
        
        // 创建新用户
        const newUser = {
          id: Date.now().toString(),
          username: this.registerForm.username,
          email: this.registerForm.email,
          password: this.registerForm.password,
          registerTime: new Date().toISOString()
        }
        
         users.push(newUser)
         localStorage.setItem('blog_users', JSON.stringify(users))
         
         // 刷新已注册用户列表
         this.loadRegisteredUsers()
         
         this.showMessage('注册成功！请登录', 'success')
         
         // 切换到登录表单并填入用户名
         setTimeout(() => {
           this.switchToLogin()
           this.loginForm.username = this.registerForm.username
           // 清空注册表单
           this.registerForm = {
             username: '',
             email: '',
             password: '',
             confirmPassword: '',
             agreeTerms: false
           }
         }, 1500)
        
      } catch (error) {
        this.showMessage('注册失败，请重试')
       } finally {
         this.isLoading = false
       }
     },
     
     // 加载已注册用户列表
     loadRegisteredUsers() {
       const users = JSON.parse(localStorage.getItem('blog_users') || '[]')
       this.registeredUsers = users.map(user => ({
         id: user.id,
         username: user.username
       }))
     },
     
     // 快速填入用户名
     quickFillUser(username) {
       if (this.isLogin) {
         this.loginForm.username = username
       }
     }
   },
   
   mounted() {
     // 检查URL参数决定显示登录还是注册
     if (this.$route.query.mode === 'register') {
       this.isLogin = false
     }
     
     // 加载已注册用户列表
     this.loadRegisteredUsers()
   }
}
</script>

<style scoped>
.auth-page {
  min-height: calc(100vh - 160px);
  display: flex;
  align-items: center;
  padding: 2rem 0;
}

.auth-card {
  border: none;
  border-radius: 1rem;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
}

.card-header {
  background: linear-gradient(135deg, #0d6efd, #6f42c1);
  color: white;
  padding: 1.5rem;
}

.card-title {
  font-size: 1.5rem;
  margin: 0;
}

.auth-switch .btn-group {
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  border-radius: 0.5rem;
  overflow: hidden;
}

.auth-switch .btn {
  border-radius: 0;
  padding: 0.75rem 2rem;
  font-weight: 500;
  transition: all 0.3s ease;
}

.auth-form {
  animation: fadeIn 0.5s ease-in-out;
}

.form-label {
  font-weight: 500;
  color: #495057;
  margin-bottom: 0.5rem;
}

.form-control {
  border-radius: 0.5rem;
  border: 2px solid #e9ecef;
  padding: 0.75rem 1rem;
  transition: all 0.3s ease;
}

.form-control:focus {
  border-color: #0d6efd;
  box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
}

.form-control.is-invalid {
  border-color: #dc3545;
  box-shadow: 0 0 0 0.25rem rgba(220, 53, 69, 0.25);
}

.input-group .form-control {
  border-radius: 0.5rem 0 0 0.5rem;
}

.input-group .btn {
  border-radius: 0 0.5rem 0.5rem 0;
  border: 2px solid #e9ecef;
  border-left: none;
}

.input-group .form-control:focus + .btn {
  border-color: #0d6efd;
}

.form-check-input {
  border-radius: 0.25rem;
  border: 2px solid #e9ecef;
}

.form-check-input:checked {
  background-color: #0d6efd;
  border-color: #0d6efd;
}

.btn-primary {
  background: linear-gradient(45deg, #0d6efd, #4285f4);
  border: none;
  border-radius: 0.5rem;
  padding: 0.75rem 1.5rem;
  font-weight: 500;
  transition: all 0.3s ease;
}

.btn-primary:hover {
  background: linear-gradient(45deg, #0b5ed7, #3367d6);
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(13, 110, 253, 0.3);
}

.btn-primary:disabled {
  background: #6c757d;
  transform: none;
  box-shadow: none;
}

.alert {
  border-radius: 0.5rem;
  border: none;
  padding: 1rem;
  margin-bottom: 0;
}

.alert-success {
  background-color: #d1edff;
  color: #0c5460;
}

.alert-danger {
  background-color: #f8d7da;
  color: #721c24;
}

.btn-close {
  filter: none;
  opacity: 0.5;
}

.btn-close:hover {
  opacity: 1;
}

.text-muted {
  font-size: 0.875rem;
  line-height: 1.4;
}

/* 动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 深色主题支持 */
.dark-theme .auth-card,
[data-theme="dark"] .auth-card {
  background: rgba(33, 37, 41, 0.95) !important;
  color: #ffffff;
}

.dark-theme .form-label,
[data-theme="dark"] .form-label {
  color: #f8f9fa;
}

.dark-theme .form-control,
[data-theme="dark"] .form-control {
  background-color: #2c3034;
  border-color: #495057;
  color: #ffffff;
}

.dark-theme .form-control:focus,
[data-theme="dark"] .form-control:focus {
  background-color: #2c3034;
  border-color: #66b3ff;
  color: #ffffff;
  box-shadow: 0 0 0 0.25rem rgba(102, 179, 255, 0.25);
}

.dark-theme .form-control.is-invalid,
[data-theme="dark"] .form-control.is-invalid {
  border-color: #dc3545;
  box-shadow: 0 0 0 0.25rem rgba(220, 53, 69, 0.25);
}

.dark-theme .form-control::placeholder,
[data-theme="dark"] .form-control::placeholder {
  color: #adb5bd;
}

.dark-theme .input-group .btn,
[data-theme="dark"] .input-group .btn {
  background-color: #495057;
  border-color: #495057;
  color: #ffffff;
}

.dark-theme .input-group .btn:hover,
[data-theme="dark"] .input-group .btn:hover {
  background-color: #5a6268;
  border-color: #5a6268;
}

.dark-theme .form-check-input,
[data-theme="dark"] .form-check-input {
  background-color: #2c3034;
  border-color: #495057;
}

.dark-theme .form-check-input:checked,
[data-theme="dark"] .form-check-input:checked {
  background-color: #66b3ff;
  border-color: #66b3ff;
}

 /* 已注册用户列表样式 */
 .registered-users-info {
   background: rgba(13, 110, 253, 0.05);
   border: 1px solid rgba(13, 110, 253, 0.2);
   border-radius: 0.5rem;
   padding: 0.75rem;
   margin-top: 1rem;
 }
 
 .user-list .badge {
   transition: all 0.3s ease;
   border: 1px solid #dee2e6;
 }
 
 .user-list .badge:hover {
   background-color: #0d6efd !important;
   color: white !important;
   transform: translateY(-1px);
   cursor: pointer;
 }
 
 /* 深色主题下的用户列表 */
 .dark-theme .registered-users-info,
 [data-theme="dark"] .registered-users-info {
   background: rgba(102, 179, 255, 0.1);
   border-color: rgba(102, 179, 255, 0.3);
 }
 
 .dark-theme .user-list .badge,
 [data-theme="dark"] .user-list .badge {
   background-color: #495057 !important;
   color: #f8f9fa !important;
   border-color: #6c757d;
 }
 
 .dark-theme .user-list .badge:hover,
 [data-theme="dark"] .user-list .badge:hover {
   background-color: #66b3ff !important;
   color: #121212 !important;
 }
 
 /* 响应式调整 */
 @media (max-width: 576px) {
   .auth-page {
     padding: 1rem 0;
   }
   
   .card-header {
     padding: 1rem;
   }
   
   .card-body {
     padding: 1.5rem !important;
   }
   
   .auth-switch .btn {
     padding: 0.6rem 1.5rem;
     font-size: 0.9rem;
   }
   
   .card-title {
     font-size: 1.25rem;
   }
   
   .registered-users-info {
     padding: 0.5rem;
   }
   
   .user-list .badge {
     font-size: 0.75rem;
     margin-bottom: 0.5rem;
   }
 }
</style>
